package org.jenkinsci.plugins.qywechat.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
	private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);
	/**
	 * 计算两个日期相差的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getDateSpace(String date1, String date2) {
		int days = 0;
		Calendar calst = Calendar.getInstance();
		Calendar caled = Calendar.getInstance();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try {
			calst.setTime(sdf.parse(date1));
			caled.setTime(sdf.parse(date2));
		} catch (ParseException e) {
			logger.error(e.getMessage(), e);
		}
		
		// 设置时间为0时
		calst.set(Calendar.HOUR_OF_DAY, 0);
		calst.set(Calendar.MINUTE, 0);
		calst.set(Calendar.SECOND, 0);
		caled.set(Calendar.HOUR_OF_DAY, 0);
		caled.set(Calendar.MINUTE, 0);
		caled.set(Calendar.SECOND, 0);
		// 得到两个日期相差的天数
		days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24 + 1;

		return days;
	}
	
	/**
     * 获取两个日期内所有日期（包含开始日期和截止日期）
     *
     * @param from 开始日期
     * @param to   截止日期
     * @return 两个日期之间的所有日期
     */
    public static String[] getAllDays(String from, String to) {
        String[] days = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            long toDay = format.parse(to).getTime();
            long fromDay = format.parse(from).getTime();
            long i = (toDay - fromDay) / (1000L * 60L * 60L * 24L);
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(format.parse(from));
            days = new String[Integer.valueOf(String.valueOf(i)) + 1];
            days[0] = from;
            for (int j = 1; j <= i; j++) {
                calendar.add(Calendar.DATE, 1);
                days[j] = format.format(calendar.getTime());
            }
        } catch (ParseException e) {
        	logger.error(e.getMessage(), e);
        }
        return days;
    }
    
    /**
     * 获取当前系统日期前一天
     * 
     * @return
     */
    public static String getCurSysDayBefore() {
    	Calendar calendar = Calendar.getInstance();
    	calendar.add(Calendar.DATE, -1);
    	Date date = calendar.getTime();
    	DateFormat df = new SimpleDateFormat("yyyyMMdd");
    	return df.format(date);
    }
    
    /**
     * 获取指定日期向前/后推迟n天的日期
     * 
     * @param specDay
     *          指定日期
     * @param diffDays
     *          推迟的天数
     * @param forwardFlag
     *          true-向前，false-向后
     * @return
     */
    public static String getSpecDiffDay(String specDay, int diffDays, boolean forwardFlag) {
    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    	String result = "";
    	try {
			Date date = format.parse(specDay);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DATE, forwardFlag ? -diffDays : diffDays);
			result = format.format(calendar.getTime());
		} catch (ParseException e) {
			logger.error(e.getMessage(), e);
		}
    	return result;
    }
    
    public static String getCurSysTime() {
    	Calendar calendar = Calendar.getInstance();
    	Date date = calendar.getTime();
    	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return df.format(date);
    }
    
    public static String getCurSysTime2() {
    	Calendar calendar = Calendar.getInstance();
    	Date date = calendar.getTime();
    	DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    	return df.format(date);
    }
    
    public static String getDateTimeFromTimeMillisAndFormatStr(long timeMillis, String formatStr) {
    	Date date = new Date(timeMillis);
    	DateFormat df = new SimpleDateFormat(formatStr);
    	return df.format(date);
    }
    
    /**
     * 日期范围切片
     * 
     * <pre>
     * --eg:
     * getSliceDateRange("201806", "201808");
     * return: [201806, 201807, 201808]
     * </pre>
     * 
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getSliceDateRange(String startDate, String endDate){
    	List<String> sliceDateRangeList = new ArrayList<>();
    	try {
			Date d1 = new SimpleDateFormat("yyyyMM").parse(startDate);
			Date d2 = new SimpleDateFormat("yyyyMM").parse(endDate);
			Calendar dd = Calendar.getInstance();
			dd.setTime(d1);// 设置日期起始时间

			while (dd.getTime().compareTo(d2) < 1) {// 判断是否到结束日期
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
				String str = sdf.format(dd.getTime());
				sliceDateRangeList.add(str);
				dd.add(Calendar.MONTH, 1);// 进行当前日期月份加1
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return sliceDateRangeList;
    }
}
